//
//  MLDiscoverSearchView.swift
//  Weibo
//
//  Created by 李亮亮 on 16/4/7.
//  Copyright © 2016年 Big Fish. All rights reserved.
//

import UIKit
import SnapKit

class MLDiscoverSearchView: UIView {
    
    
    var tf = UITextField()
    var btn = UIButton()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        btn.setTitle("取消", forState: .Normal)
//        btn.backgroundColor = UIColor.orangeColor()
        btn.setTitleColor(UIColor.orangeColor(), forState: .Normal)
        btn.titleLabel?.font = UIFont.systemFontOfSize(17)
        btn.addTarget(self, action: #selector(MLDiscoverSearchView.cancelBtnDidClick), forControlEvents: .TouchUpInside)
        addSubview(btn)

        
        tf.placeholder = "听说,在黑黑的夜里,电影和黄瓜更配哟~"
        tf.backgroundColor = UIColor.init(red: 0.7, green: 0.7, blue: 0.7, alpha: 1.0)
        tf.layer.cornerRadius = 8
        tf.layer.masksToBounds = true
        
        tf.leftView = UIImageView(image: UIImage(named: "searchbar_textfield_search_icon"))
        tf.leftView?.frame = CGRectMake(0, 0, self.bounds.height, self.bounds.height)
        tf.leftView?.contentMode = .Center
        tf.leftViewMode = .Always
        
        tf.addTarget(self, action: #selector(MLDiscoverSearchView.editingDidBegin), forControlEvents: UIControlEvents.EditingDidBegin)
        addSubview(tf)
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func layoutSubviews() {
        
        tf.snp_makeConstraints { (make) in
            make.top.equalTo(self.snp_top)
            make.bottom.equalTo(self.snp_bottom)
            make.left.equalTo(self.snp_left)
            make.right.equalTo(self.snp_right)
        }
        
        btn.snp_makeConstraints { (make) in
            make.top.equalTo(self.snp_top)
            make.bottom.equalTo(self.snp_bottom)
            make.right.equalTo(self.snp_right)
        }
        
    }
    
    
    class func loadSearchView() -> MLDiscoverSearchView{
        
        let v = MLDiscoverSearchView(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.width - 5, 35))
        return v
    }
    
    
    @objc private func editingDidBegin() {
        
        print("WTF")
        
        UIView.animateWithDuration(0.25) {
            self.tf.frame = CGRectMake(0, 0, self.bounds.width - self.btn.frame.size.width - 6, self.bounds.height)
        }
    }
    
    
    @objc private func cancelBtnDidClick() {
        
        self.tf.resignFirstResponder()
//        endEditing(true)
        
        UIView.animateWithDuration(0.25) {
            self.tf.frame = CGRectMake(0, 0, self.bounds.width, self.bounds.height)
        }
    }
    
    
}
